package com.nowcoder.community.service;

import com.nowcoder.community.dao.elasticsearch.DiscussPostRepository;
import com.nowcoder.community.entity.DiscussPost;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xiexu
 * @create 2022-07-10 22:09
 */
@Service
public class ElasticsearchService {

    @Autowired
    private DiscussPostRepository discussRepository;

    @Autowired
    private ElasticsearchTemplate elasticTemplate;

    /**
     * 将帖子信息保存到es
     *
     * @param post
     */
    public void saveDiscussPost(DiscussPost post) {
        discussRepository.save(post);
    }

    /**
     * 在es中删除对应id的帖子
     *
     * @param id
     */
    public void deleteDiscussPost(int id) {
        discussRepository.deleteById(id);
    }

    /**
     * 根据关键字搜索帖子
     *
     * @param keyword 关键字
     * @param current 当前显示第几页，从0开始
     * @param limit   每页显示多少条数据
     * @return
     */
    public Page<DiscussPost> searchDiscussPost(String keyword, int current, int limit) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                // 只在title和content字段进行搜索
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
                // 优先根据type字段进行倒序排序
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                // 然后根据score字段进行倒序排序
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                // 最后根据createTime字段进行倒序排序
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                // 从第几页开始，每页显示多少条数据
                .withPageable(PageRequest.of(current, limit))
                // 高亮显示字段
                .withHighlightFields(
                        // 对title字段进行高亮显示，在前端页面显示<em>title信息</em>
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        // 对content字段进行高亮显示，在前端页面显示<em>content信息</em>
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")).build();

        Page<DiscussPost> page = elasticTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {
                // 先获取这次搜索命中的数据
                SearchHits hits = response.getHits();
                // 如果没查到数据就直接返回null
                if (hits.getTotalHits() <= 0) {
                    return null;
                }

                List<DiscussPost> list = new ArrayList<>();
                // 遍历搜索命中的数据
                for (SearchHit hit : hits) {
                    DiscussPost post = new DiscussPost();

                    String id = hit.getSourceAsMap().get("id").toString();
                    post.setId(Integer.valueOf(id));

                    String userId = hit.getSourceAsMap().get("userId").toString();
                    post.setUserId(Integer.valueOf(userId));

                    // 这是原始的title，并不是高亮显示的title，高亮显示的下面单独处理
                    String title = hit.getSourceAsMap().get("title").toString();
                    post.setTitle(title);

                    String content = hit.getSourceAsMap().get("content").toString();
                    post.setContent(content);

                    String status = hit.getSourceAsMap().get("status").toString();
                    post.setStatus(Integer.valueOf(status));

                    String createTime = hit.getSourceAsMap().get("createTime").toString();
                    post.setCreateTime(new Date(Long.valueOf(createTime)));

                    String commentCount = hit.getSourceAsMap().get("commentCount").toString();
                    post.setCommentCount(Integer.valueOf(commentCount));

                    // 处理高亮显示的结果
                    // 获取与title有关的高亮显示的内容
                    HighlightField titleField = hit.getHighlightFields().get("title");
                    if (titleField != null) {
                        // 高亮有可能是多个数据，所以我们这里只设置第一个数据高亮即可
                        post.setTitle(titleField.getFragments()[0].toString());
                    }

                    // 获取与content有关的高亮显示的内容
                    HighlightField contentField = hit.getHighlightFields().get("content");
                    if (contentField != null) {
                        // 高亮有可能是多个数据，所以我们这里只设置第一个数据高亮即可
                        post.setContent(contentField.getFragments()[0].toString());
                    }

                    list.add(post);
                }

                return new AggregatedPageImpl(list, pageable, hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore());
            }
        });

        return page;
    }

}
